#include "head.h"

int pipe_fd[2];
void func(int num){
    write(pipe_fd[1], "1", 1);
}

int main(int argc,char*argv[])
{
    pipe(pipe_fd);

    if(fork() != 0){
        signal(2, func);

        sleep(5);
         pid_t ret_wait = wait(NULL);
         printf("%d\n", ret_wait);
         ERROR_CHECK(ret_wait, -1, "wait");
         exit(0);
    }

    //子进程
    setpgid(0, 0);

    pool_t pool;
    initPool(&pool, 3);

    //从配置文件读取信息
    char ip[20];
    char port[10];
    memset(ip, 0, sizeof(ip));
    memset(port, 0, sizeof(port));
    getparameter("ip", ip);
    getparameter("port", port);
    //printf("port=%s\n", port);
    
    int socket_fd;
    initSocket(&socket_fd, ip, port);

    //printf("子进程before addepoll\n");
    int epoll_fd = epoll_create(1);
    addEpoll(epoll_fd, socket_fd);

    addEpoll(epoll_fd, pipe_fd[0]);
    //printf("子进程while\n");
    while(1){
        struct epoll_event list[5];
        int epoll_num = epoll_wait(epoll_fd, list, 5, -1);


        for(int i=0; i<epoll_num; i++){

            if(list[i].data.fd == pipe_fd[0]){
                // 有信号-> 父进程 ->管道-> epoll
                char buf[60] = {0};
                read(pipe_fd[0], buf, sizeof(buf));

                printf("子进程的主线程, 知道了信号过来 \n");
                // 修改退出标记位
                pthread_mutex_lock(&pool.lock);
                pool.exitFlag = 1;
                pthread_cond_broadcast(&pool.cond);
                pthread_mutex_unlock(&pool.lock);

                // 捕捉所有子线池的退出
                for(int j=0; j<pool.num; j++){
                    pthread_join(pool.list[i], NULL);
                }

                printf("所有子线程退出 \n");
                pthread_exit(NULL);

            } else if(list[i].data.fd == socket_fd){
                // 有新的客户端链接到来

                printf("new connect\n");
                int net_fd = accept(socket_fd, NULL, NULL);

                // 加锁: 队列属于主线程和子线程的共享资源
                // 把net_fd放入任务队列
                pthread_mutex_lock(&pool.lock);
                //printf("enQueue before \n");
                enQueue(&pool.queue, net_fd); 
                // 通过广播把子线程唤醒: 取队列的人物去执行
                pthread_cond_broadcast(&pool.cond);
                //printf("enQueue after \n");
                // 释放锁
                pthread_mutex_unlock(&pool.lock);
            }
        }
    }
    return 0;
}

